//
//  ZFJPopManager.m
//  GSDemo
//
//  Created by ZhangFujie on 2022/10/12.
//

#import "ZFJPopManager.h"
#import "ZFJPopModel.h"
#import "ZFJPopView.h"

@interface ZFJPopManager ()

/// 正在弹出的弹出model
@property (nonatomic,strong,readwrite) ZFJPopModel *currentPopModel;

/// 正在弹出的弹出popview
@property (nonatomic,strong,readwrite) ZFJPopView *currentPopView;

/// 数据源数组
@property (nonatomic,strong) NSMutableArray<ZFJPopModel *> *dataArray;

/// 弹窗视图数组
@property (nonatomic,strong) NSMutableArray<ZFJPopView *> *popViewArray;

/// 父视图
@property (nonatomic,strong) UIView *topView;

/// 发送验证码定时器
@property (nonatomic,strong) NSTimer *myTimer;

/// 倒计时
@property (nonatomic,assign) NSInteger countDownCount;

/// 是否正着弹出中...
@property (nonatomic,assign,readwrite) BOOL isWorking;

@end

@implementation ZFJPopManager

static ZFJPopManager *_instance;
static dispatch_once_t _onceToken;

/// 销毁单利
+ (void)destroy{
    _onceToken = 0;
    _instance = nil;
}

+ (ZFJPopManager *)sharedInstance{
    dispatch_once(&_onceToken, ^{
        _instance = [[super allocWithZone:NULL]init];
    });
    return _instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    return [ZFJPopManager sharedInstance];
}

- (instancetype)copyWithZone:(struct _NSZone *)zone{
    return [ZFJPopManager sharedInstance];
}

#pragma mark - public

/// 开始弹框
- (void)startPopView{
    [self startPopView:self.zfj_keyWindow];
}

- (void)startPopView:(UIView *)topView{
    if(self.isWorking){
        if(self.popErrorCodeBlock){
            self.popErrorCodeBlock(ZFJPopWorkingCode);
        }
        return;
    }
    self.topView = topView;
    if(self.isEmpty){
        if(self.popErrorCodeBlock){
            self.popErrorCodeBlock(ZFJPopNoModelsCode);
        }
        return;
    }
    [self popNewView];
    /// 记录正着弹窗中...
    self.isWorking = YES;
}


/// 停止弹框
- (void)stopPopView{
    [self.dataArray removeAllObjects];
    [self.popViewArray removeAllObjects];
    [self.currentPopView removeFromSuperview];
    self.currentPopModel = nil;
    /// 弹窗停止，记录状态
    self.isWorking = NO;
}

/// 有新的数据进来继续弹窗
- (void)goOnPopView{
    if(self.isWorking && self.currentPopView == nil){
        [self popNewView];
    }
}

/// 开始弹出下一个
- (void)popNewView{
    if(self.currentPopView != nil){
        [self.currentPopView removeFromSuperview];
        self.currentPopView = nil;
    }
    
    /// 要是没有了就回调完成，但是不要停止，有新的弹窗进来还要继续工作
    if(self.isEmpty){
        if(self.popFinishedBlock){
            self.popFinishedBlock();
        }
        return;
    }
    
    /// 如果有定时器先关了
    [self stopMyTimer];
    
    self.currentPopModel = [self.dataArray firstObject];
    ZFJPopWeakSelf;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.currentPopModel.popDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        weakSelf.currentPopView = [weakSelf.popViewArray firstObject];
        [weakSelf.currentPopView showPopAnimationView];
        [weakSelf.topView addSubview:weakSelf.currentPopView];
        /// 移除数据源
        [weakSelf.dataArray removeObject:weakSelf.currentPopModel];
        [weakSelf.popViewArray removeObject:weakSelf.currentPopView];
    });
}

/// 根据model创建弹窗
- (void)createPopViewWithModel:(ZFJPopModel *)model index:(NSInteger)index{
    if(model.customPopView == nil){
        if(self.popErrorCodeBlock){
            self.popErrorCodeBlock(ZFJPopNoCurrentViewNillCode);
        }
        return;
    }
    ZFJPopWeakSelf;
    ZFJPopView *popView = [[ZFJPopView alloc] initWithPopView:model.customPopView topView:self.topView];
    popView.disableBackgroundClick = model.disableBackgroundClick;
    popView.backgroundColor = model.popViewBackgroundColor;
    popView.animateStyle = model.animateStyle;
    popView.viewWillAppear = ^{
        if(weakSelf.viewWillAppear){
            weakSelf.viewWillAppear(model);
        }
        if(model.countDownStop > 0){
            [weakSelf startMyTimer:model.countDownStop];
        }
    };
    popView.viewDidAppear = ^{
        if(weakSelf.viewDidAppear){
            weakSelf.viewDidAppear(model);
        }
    };
    popView.viewWillDisappear = ^{
        if(weakSelf.viewWillDisappear){
            weakSelf.viewWillDisappear(model);
        }
    };
    popView.viewDidDisappear = ^{
        if(weakSelf.viewDidDisappear){
            weakSelf.viewDidDisappear(model);
        }
        [weakSelf popNewView];
    };
    if(index == -1){
        [self.popViewArray addObject:popView];
    }else{
        [self.popViewArray insertObject:popView atIndex:index];
    }
}

/// 开启定时器
- (void)startMyTimer:(NSInteger)count{
    _countDownCount = count;
    _myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(myTimerSelector) userInfo:nil repeats:YES];
}

/// 定时器事件
- (void)myTimerSelector{
    if (_countDownCount == 0){
        [self stopMyTimer];
        [self.currentPopView hidePopAnimationView];
    }else{
        _countDownCount --;
    }
    if(self.popCountDownBlock){
        self.popCountDownBlock(_currentPopModel, _countDownCount);
    }
}

/// 停止定时器
- (void)stopMyTimer{
    if(_myTimer != nil){
        [_myTimer invalidate];
        _myTimer = nil;
    }
}

#pragma mark - dataSource
- (void)addPopModel:(ZFJPopModel *)model{
    [self.dataArray addObject:model];
    [self createPopViewWithModel:model index:-1];
    [self goOnPopView];
}

- (void)addPopModelsFromArray:(NSArray<ZFJPopModel *> *)otherArray{
    ZFJPopWeakSelf;
    [self.dataArray addObjectsFromArray:otherArray];
    for (ZFJPopModel *model in otherArray) {
        [weakSelf createPopViewWithModel:model index:-1];
    }
    [self goOnPopView];
}

- (void)removePopModel:(ZFJPopModel *)model{
    NSInteger index = [self.dataArray indexOfObject:model];
    [self.dataArray removeObject:model];
    [self.popViewArray removeObjectAtIndex:index];
}

- (void)removePopModelAtIndex:(NSUInteger)index{
    [self.dataArray removeObjectAtIndex:index];
    [self.popViewArray removeObjectAtIndex:index];
}

- (void)removeAllPopModels{
    [self.dataArray removeAllObjects];
    [self.popViewArray removeAllObjects];
}

#pragma mark - getter
- (BOOL)isEmpty{
    if(self.dataArray.count == 0 || self.popViewArray.count == 0){
        return YES;
    }
    return NO;
}

- (UIWindow *)zfj_keyWindow{
    UIWindow *keyWindow = nil;
    NSArray *windows = [[UIApplication sharedApplication] windows];
    for (UIWindow  *window in windows) {
        if (window.isKeyWindow) {
            keyWindow = window;
            break;
        }
    }
    return keyWindow;
}

#pragma mark - 懒加载
- (NSMutableArray<ZFJPopModel *> *)dataArray{
    if(_dataArray == nil){
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (NSMutableArray<ZFJPopView *> *)popViewArray{
    if(_popViewArray == nil){
        _popViewArray = [[NSMutableArray alloc] init];
    }
    return _popViewArray;
}

@end
